package com.example.lastwork2.adapter;

import android.content.Context;
import android.hardware.camera2.params.OisSample;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.example.lastwork2.MainActivity;
import com.example.lastwork2.R;
import com.example.lastwork2.cart.CartActivity;
import com.example.lastwork2.fragments.detail.ShopDetailActivity;
import com.example.lastwork2.model.Shop;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class CartAdapter extends BaseAdapter {

    //获取上下文环境
    private Context context;
    //获取item布局
    private int layoutId;
    //数据源
    private List<Shop> shops;

    //用于备份全局变量  cartShop
    private List<Shop> cartShop = ShopDetailActivity.cartShop;
    //用于备份全局变量  curnum
    private List<Integer> curnum = ShopDetailActivity.curnum;

    //用于存储购物车的所有商品信息，不去重   结算是创建新订单时使用
    private List<Shop> cartShop1 ;

    public CartAdapter(){}
    public CartAdapter(Context context, int layoutId, List<Shop> shops) {
        this.context = context;
        this.layoutId = layoutId;
        this.shops = shops;
    }

    @Override
    public int getCount() {
        return shops.size();
    }

    @Override
    public Object getItem(int position) {
        return shops.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //获取布局文件对象
        View view = LayoutInflater.from(context).inflate(layoutId,null);
        //获取布局文件的控件对象
        ImageView imgview = view.findViewById(R.id.cart_image);
        TextView tital = view.findViewById(R.id.cart_name);
        TextView brief = view.findViewById(R.id.cart_brief);
        TextView price = view.findViewById(R.id.if_price);
        ImageButton add = view.findViewById(R.id.imgbtn_add);
        ImageButton sub = view.findViewById(R.id.imgbtn_sub);
        EditText count = view.findViewById(R.id.shop_count);

        //加载购物车页面时显示以前的数值
        count.setText(ShopDetailActivity.curnum.get(position)+"");
        //获取数据源中当前元素的位置
        Shop sho = shops.get(position);

        //把数据显示到对应的控件中去
        //显示图片
        Glide.with(context)
                .load(sho.getIcon())
                .into(imgview);
        tital.setText(sho.getShopName());
        brief.setText(sho.getShopBrief());
        String sumprice = String.valueOf(sho.getPrice());
        price.setText(sumprice);

        //实现商品数量的加减

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer integer = curnum.get(position) + 1;
                ShopDetailActivity.curnum.set(position,integer);
                count.setText(integer+"");




                //结算
                //获取商品总金额
                CartActivity.sumPrice=0.0;
                for(int i = 0;i<curnum.size();i++){
                    //获取i位置的商品数量
                    int counti = (int) ShopDetailActivity.curnum.get(i);
                    //获取i位置的商品价格
                    double pricei = Double.parseDouble(String.valueOf(cartShop.get(i).getPrice()));
                    //计算总金额
                    CartActivity.sumPrice = CartActivity.sumPrice + (counti * pricei);
                    CartActivity.sumPrice = (double)Math.round(CartActivity.sumPrice*100)/100;
                }
                CartActivity.sumPriceKongJian.setText(CartActivity.sumPrice+"");

                //更新数据库中购物车的数据
                //将购物车数据和商品对应数量发送到数据库
                sendCartToServer(cartShop,curnum);

            }
        });

        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ShopDetailActivity.curnum.get(position)>0){
                    Integer integer = curnum.get(position) - 1;
                    ShopDetailActivity.curnum.set(position,integer);
                    count.setText(integer+"");
                }
                //删除逻辑
                if (ShopDetailActivity.curnum.get(position) == 0){
                    Shop itmStr = ShopDetailActivity.cartShop.get(position);
                    ShopDetailActivity.cartShop.remove(itmStr);
                    Integer i = ShopDetailActivity.curnum.get(position);
                    ShopDetailActivity.curnum.remove(i);
                    notifyDataSetChanged();
                }




//                //获取商品总金额
                CartActivity.sumPrice=0.0;
                for(int i = 0;i<curnum.size();i++){
                    //获取i位置的商品数量
                    int counti = (int)ShopDetailActivity.curnum.get(i);
                    //获取i位置的商品价格
                    double pricei = Double.parseDouble(String.valueOf(ShopDetailActivity.cartShop.get(i).getPrice()));
                    //计算总金额
                    CartActivity.sumPrice = CartActivity.sumPrice + (counti * pricei);
                    CartActivity.sumPrice = (double) Math.round(CartActivity.sumPrice*100)/100;
                }
                CartActivity.sumPriceKongJian.setText(CartActivity.sumPrice+"");

                //更新数据库中购物车的数据
                //将购物车数据和商品对应数量发送到数据库
                sendCartToServer(cartShop,curnum);

            }


        });





        //结算
        //点击结算要将当前购物车的商品信息，及cartshop集合中的商品信息创建一个订单
        //并发送到数据库中，
        CartActivity.buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                cartShop1 = new ArrayList<>();
                //将每一个商品信息都作为一条数据存入cartShop1集合中
                for(int i = 0;i<cartShop.size();i++){
                    for(int j = 0; j< curnum.get(i);j++){
                        cartShop1.add(cartShop.get(i));
                    }
                }
                //检验逻辑
                System.out.println("订单中的商品数量:"+cartShop1.size());



                //向数据库发送购物车中商品信息,创建一个订单
                sendToServer(cartShop1);
                //弹窗提示 购买成功
                new AlertDialog.Builder(context)
                        .setTitle("购买成功")
                        .setMessage("您一共花费：￥"+CartActivity.sumPrice)
                        .show();
                //向服务器发送请求删除购物车中的信息，向服务器传空集合
                //更新数据库中购物车的数据
                //将购物车数据和商品对应数量发送到数据库
                cartShop = new ArrayList<>();
                curnum = new ArrayList<>();
                sendCartToServer(cartShop,curnum);


                ShopDetailActivity.cartShop.clear();
                ShopDetailActivity.curnum.clear();
                CartActivity.sumPriceKongJian.setText("￥"+0.0);
                notifyDataSetChanged();



            }
        });



        return view;
    }

    private void sendCartToServer(List<Shop> cartShop, List<Integer> curnum) {
        String url1 = "http://10.0.2.2:8080/bigwork/cart";

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();

                    HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();
                    connection.setRequestMethod("POST");
                    //向服务器发送json数据
                    OutputStream os = connection.getOutputStream();
                    //发送cartShop数据
                    String jsonData = gson.toJson(cartShop);
                    os.write(jsonData.getBytes());
                    os.flush();
                    //发送curnum数据
                    String jsonCurnum = gson.toJson(curnum);
                    os.write(jsonCurnum.getBytes());
                    os.flush();
                    //发送userId
                    String jsonUserId = gson.toJson(MainActivity.userId);
                    os.write(jsonUserId.getBytes());
                    os.flush();
                    os.close();

                    //接受服务器传来的数据
                    InputStream inputStream = connection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();



    }


    private void sendToServer(List<Shop> cartShop1) {

        String url1 = "http://10.0.2.2:8080/bigwork/order";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
                    String jsonData = gson.toJson(cartShop1);

                    HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();
                    connection.setRequestMethod("POST");
                    //向服务器发送json数据
                    OutputStream os = connection.getOutputStream();
                    os.write(jsonData.getBytes());
                    os.flush();

                    String jsonUserId = gson.toJson(MainActivity.userId);
                    os.write(jsonUserId.getBytes());
                    os.flush();

                    os.close();




                    //接受服务器传来的数据
                    InputStream inputStream = connection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();


    }

}
